#!/usr/bin/env python3
"""
gobject-introspection MCP Server

面向软件：gobject-introspection
提供对 gobject-introspection 命令行操作的 MCP 工具封装

MCP tools 列表：
1. gobject_introspection_compile_and_run
   - 用途：编译并运行使用 gobject-introspection 的 C 测试程序
   - 参数：无
   - 返回：统一的 JSON 结构，包含命令执行结果
"""

from mcp.server.fastmcp import FastMCP, Context
import subprocess
import tempfile
import os

mcp = FastMCP("GObject-Introspection MCP Server")

@mcp.tool()
def gobject_introspection_compile_and_run() -> dict:
    """
    编译并运行使用 gobject-introspection 的 C 测试程序
    
    创建一个简单的 C 程序，使用 pkg-config 获取 gobject-introspection 编译参数，
    编译程序并运行验证 GObject 类型系统功能。
    
    返回 JSON 结构：
    {
        "success": bool,      # 操作是否成功
        "command": str,       # 执行的命令
        "exit_code": int,     # 命令退出码
        "stdout": str,        # 标准输出
        "stderr": str         # 标准错误
    }
    """
    try:
        # 创建临时目录和工作文件
        with tempfile.TemporaryDirectory() as temp_dir:
            # 创建测试 C 文件
            test_c_path = os.path.join(temp_dir, "test.c")
            test_c_content = '''#include <glib-object.h>

int main() {
  GType type = G_TYPE_OBJECT;
  const gchar* type_name = g_type_name(type);
  g_print("Type name: %s\\n", type_name);
  return 0;
}'''
            
            with open(test_c_path, 'w') as f:
                f.write(test_c_content)
            
            # 使用 pkg-config 获取编译参数并编译
            pkg_config_cmd = "pkg-config --cflags --libs gobject-introspection-1.0"
            compile_cmd = f"{pkg_config_cmd} | xargs gcc -o {temp_dir}/test {test_c_path}"
            
            # 执行编译命令
            compile_result = subprocess.run(
                compile_cmd, 
                shell=True, 
                capture_output=True, 
                text=True,
                cwd=temp_dir
            )
            
            if compile_result.returncode != 0:
                return {
                    "success": False,
                    "command": compile_cmd,
                    "exit_code": compile_result.returncode,
                    "stdout": compile_result.stdout,
                    "stderr": compile_result.stderr
                }
            
            # 运行编译后的程序
            run_cmd = f"{temp_dir}/test"
            run_result = subprocess.run(
                run_cmd,
                shell=True,
                capture_output=True,
                text=True
            )
            
            return {
                "success": run_result.returncode == 0 and "Type name: GObject" in run_result.stdout,
                "command": f"{compile_cmd} && {run_cmd}",
                "exit_code": run_result.returncode,
                "stdout": run_result.stdout,
                "stderr": run_result.stderr
            }
            
    except Exception as e:
        return {
            "success": False,
            "command": "gobject_introspection_compile_and_run",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Exception occurred: {str(e)}"
        }

if __name__ == "__main__":
    mcp.run()